// 首页

import './index.less';
import {Image, View} from '@tarojs/components';
import {useEffect} from "react";
import {GLOBAL_IMAGE} from "../../constant/contant";
import {utils} from "../../utils/utils";
import {FieldItem} from "../../components/homepageCmpt";
import {Api} from "../../api/api";
import {connect} from "react-redux";
import { set as setGlobalData } from '../../utils/global_data';
import {doSetUser} from "../../actions/global";
import Taro from "@tarojs/taro";
import {refreshUserInfo, wxActions} from "../../utils/wxActions";

// Index页面
function Homepage(props) {
    const {reduxUserInfo, dispatch} = props;

    // 判断token是否有效
    const isEffective = () => {
        const cacheEffectiveTime = Taro.getStorageSync('cacheEffectiveTime');
        const now = new Date().getTime();
        const cacheTime = new Date(cacheEffectiveTime.replace(/-/g, "/")).getTime();
        if (cacheEffectiveTime && now < cacheTime) {
            return true;
        }
        return false;
    }

    useEffect(() => {
        const cacheToken = Taro.getStorageSync('cacheToken');
        // 判断token是否有效
        if (cacheToken && isEffective()) {
            setGlobalData("token", cacheToken);
            wxActions.refreshUserInfo(dispatch); // 刷新用户信息
        } else {
            wxActions.autoLogin(dispatch);
        }
    }, []);

    const fieldRow1 = <View
        className={utils.classNames("fieldRow", "fieldRow1")}>
        <FieldItem imgUrl={GLOBAL_IMAGE.field_1} fieldId={1}/>
        <FieldItem imgUrl={GLOBAL_IMAGE.field_2} fieldId={2}/>
        <FieldItem imgUrl={GLOBAL_IMAGE.field_3} fieldId={3}/>
    </View>;

    const fieldRow2 = <View
        className={utils.classNames("fieldRow", "fieldRow2")}>
        <FieldItem imgUrl={GLOBAL_IMAGE.field_4} fieldId={4}/>
        <FieldItem imgUrl={GLOBAL_IMAGE.field_5} fieldId={5}/>
        <FieldItem imgUrl={GLOBAL_IMAGE.field_6} fieldId={6}/>
    </View>;

    const fieldRow3 = <View
        className={utils.classNames("fieldRow", "fieldRow3")}>
        <FieldItem imgUrl={GLOBAL_IMAGE.field_7} fieldId={7}/>
        <FieldItem imgUrl={GLOBAL_IMAGE.field_8} fieldId={8}/>
        <FieldItem imgUrl={GLOBAL_IMAGE.field_9} fieldId={9}/>
    </View>

    return (
        <View className='homepage'>
            <View className={"bg_top"}>
                <Image src={GLOBAL_IMAGE.homepage_top}/>
            </View>
            <View className={"fieldBox"}>
                {fieldRow1}
                {fieldRow2}
                {fieldRow3}
            </View>
            <View className={"bg_bot"}>
                <Image src={GLOBAL_IMAGE.homepage_bot}/>
            </View>
        </View>
    )
}

const mapStateToProps = (state) => ({
    reduxUserInfo: state.userState.reduxUserInfo
})

export default connect(mapStateToProps)(Homepage);

